package br.com.mynage.dao.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;

import org.hibernate.Session;

import br.com.mynage.dao.ISprintDAO;
import br.com.mynage.dominio.Projeto;
import br.com.mynage.dominio.Sprint;
import br.com.mynage.exception.DaoException;

public class SprintDaoImpl extends GenericDaoImpl<Sprint>  implements ISprintDAO{

	@SuppressWarnings("unchecked")
	public List<Sprint> findSprintsByProjeto(Projeto projeto) throws DaoException{
		EntityManager manager = getEntityManager();
		List<Sprint> resul = new ArrayList<Sprint>();
		
		try {  
			
			Session session = (Session) manager.getDelegate();
			
			String sql = "SELECT s.id, s.nome, s.id_projeto, p.nome, s.descricao, s.data FROM sprint s " +
					"inner join projeto p on p.id = s.id_projeto " +
					"WHERE p.id = " + projeto.getId();
			
			List<Object[]> rs = session.createSQLQuery(sql).list();
			
			for(Object o[]:rs) {
				int i = 0;
				Sprint s = new Sprint();
				s.setId((Integer)o[i++]);
				s.setNome((String)o[i++]);
				s.setProjeto(new Projeto());
				s.getProjeto().setId((Integer)o[i++]);
				s.getProjeto().setNome((String)o[i++]);
				s.setDescricao((String)o[i++]);
				s.setData((Date)o[i++]);
				resul.add(s);
			}

			return resul; 
		} catch (Exception e) {
			e.printStackTrace();
			throw new DaoException();
		} finally {
			if (manager != null) 
				manager.close(); 
		}
	}

	@Override
	public Class<Sprint> getClassType() {
		return Sprint.class;
	}

}
